package com.niubility.controller;

import com.niubility.entity.Datas;
import com.niubility.entity.SearchMain;
import com.niubility.exception.CustomException;
import com.niubility.server.IDataServer;
import com.niubility.server.Impl.SearchServer;
import com.niubility.vo.LoadAll;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/*
    资料的控制类型
 */
@RestController
public class DatasContorller {
    @Autowired
    private IDataServer dataServer;

    @Resource
    private SearchServer searchServer;
    Logger logger = Logger.getLogger(DatasContorller.class);
    /*
    * @Author:John
    * @Description:获取可得到的最大的页数
    * @Date: John 2018/1/28
    * @Params: 分页数，数据类型
    * @Return: 最大页数
    */
    public int getMaxPage(int num,String type){
       return dataServer.PageNumByType(num,type);
    }
    /*
    * @Author:John
    * @Description: 获取分页信息
    * @Date: John 2018/1/27
    * @Params: 传入分页对象
    * @Return: 返回所需页数信息
    * 测试通过
    */
    @RequestMapping("/DatasLoadAll")
    public void DatasLoadAll(HttpServletResponse response,HttpServletRequest request){
        String callback = request.getParameter("callback");
        response.setCharacterEncoding("utf-8");//发送数据格式
        String result = null;
        try {
            int num = Integer.parseInt(request.getParameter("num"));
            String type = request.getParameter("type");
            int pageMore = this.getMaxPage(num,type);
            int nowPage = Integer.parseInt(request.getParameter("nowPage"));
            List<Datas> list = dataServer.LoadAll((nowPage-1)*num,num,type);
            LoadAll loadAll = new LoadAll();
            loadAll.setPageMore(pageMore);
            loadAll.setList(list);
            result = callback + "("+ JSONObject.fromObject(loadAll).toString()+")";
            ////System.out.println(result);
        }catch (Exception e){
            logger.debug("获取数据失败");
            result = callback + "("+"{\"returncade\":"+"108}"+")";
        }
        try{
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("发送失败."+e);
        }
    }
    /*
    * @Author:John
    * @Description: 存储操作
    * @Date: John 2018/1/27
    * @Params: 存储的数据对象
    * @Return: 是否存储成功
    * 测试通过
    */
    @RequestMapping("/DatasSave")
    public void DatasSave(HttpServletResponse response,HttpServletRequest request) throws CustomException {
        Datas datas = new Datas();
        int userId = 0;
        String callback = request.getParameter("callback");
        String result=null;
        try {
            userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+103+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }

        //datas.setUserId(Integer.parseInt(request.getParameter("userId")));
        datas.setDepId(userId);
        String daName = request.getParameter("daName");
        datas.setDaName(daName);
        datas.setDaUrl(request.getParameter("daUrl"));
        datas.setDaMark(request.getParameter("daMark"));
        String daInfo = request.getParameter("daInfo");
        datas.setDaInfo(daInfo);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        datas.setDaDate(dateFormat.format(new Date()));
        try{
            ////System.out.println(datas.toString());
            boolean bool = dataServer.Save(datas);
            //es同步数据存储
            SearchMain searchMain = new SearchMain("niubility","serchMain",dataServer.LastInsertId(),daName,daInfo);
            searchServer.InsertInto(searchMain);
            ////System.out.println(bool);
            result = callback+"("+"{\"returncade\":"+"100}"+")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
        }
        try {
            ////System.out.println(result);
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("发送失败."+e);
        }
    }
    /*
    * @Author:John
    * @Description: 删除操作
    * @Date: John 2018/1/27
    * @Params: 传入 删除的id值
    * @Return:是否删除成功
    * 测试通过
    */
    @RequestMapping("/DatasDelete")
    public void DatasDelete(HttpServletResponse response,HttpServletRequest request){
        int id = Integer.parseInt(request.getParameter("daId"));
        String callback = request.getParameter("callback");
        boolean bool = dataServer.Delete(id);
        String result = null;
        if (bool) result = callback+"("+"{\"returncade\":"+"100}"+")";
        else result = callback+"("+"{\"returncade\":"+"108}"+")";
        try {
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("删除失败."+e);
        }
    }
    /*
    * @Author:John
    * @Description: 查找方式
    * @Date: John 2018/1/27
    * @Params: 传入查找参数的ID
    * @Return: 返回查找 到的条目
    * 测试通过
    */
    @RequestMapping("/DatasSelect")
    public void DatasSelect(HttpServletResponse response,HttpServletRequest request) throws IOException{
        int id = Integer.parseInt(request.getParameter("daId"));
        response.setCharacterEncoding("utf-8");//发送数据格式
        String callback = request.getParameter("callback");
        String result = null;
        //System.out.println(id+"--"+callback);
        try{
            boolean booltra = dataServer.Auto(id);//自增访问量
            Datas datas = dataServer.select(id);
            //System.out.println(datas.toString());
            //System.out.println(booltra);
            result = callback + "("+JSONObject.fromObject(datas).toString()+")";
            //System.out.println(result);
        }catch (Exception e){
            logger.debug("消息返回失败."+e);
            result = callback + "("+"{\"returncade\":"+"108}"+")";
        }
        response.getWriter().write(result);
    }
    /*
     * @Author:John
     * @Description: 获取热点信息
     * @Date: John 2018/2/1
     * @Params:
     * @Return:
     */
    @RequestMapping("/DatasHot")
    public void LoadHot(HttpServletRequest request,HttpServletResponse response){
        String callback = request.getParameter("callback");
        response.setCharacterEncoding("utf-8");
        int num = Integer.parseInt(request.getParameter("num"));
        String result = null;
        try{
            List<Datas> list = dataServer.LoadHot(num);
            result = callback+"("+JSONArray.fromObject(list).toString()+")";
        }catch (Exception e){
            logger.debug("获取失败."+e);
            result = callback+"("+"{\"returncade\":"+"108}"+")";
        }
        try{
            response.getWriter().write(result);
        }catch (IOException e){
            logger.debug("传输失败."+e);
        }
    }
}
